﻿/// <reference path="//Microsoft.WinJS.1.0/js/base.js" />
/// <reference path="//Microsoft.WinJS.1.0/js/ui.js" />
/// <reference path="../../js/Structures/FolioFixer_DataTypes.js" />
/// <reference path="../../js/Data Access/FolioFixer_DataSources.js" />
/// <reference path="../../js/Data Access/ResourceManager.js" />
(function () {
    "use strict";

    var marketCapRegex = /^(\d+(.\d+)?)([MBT])$/;
    var percentRegex = /^([\+\-])(\d+(.\d+)?)\%$/

    WinJS.UI.Pages.define("/pages/home/home.html", {
        // This function is called whenever a user navigates to this page. It
        // populates the page elements with the app's data.
        ready: function (element, options) {
            // TODO: Initialize the page here.

            document.querySelector("#portfolioList").addEventListener("iteminvoked", navFromList);

            document.getElementById("portfolioList").addEventListener("selectionchanged", manageSelected);

            document.getElementById("addButton").addEventListener("click", doClickAdd, false);

            document.getElementById("dowButton").addEventListener("click", clickDowAdd, false);

            document.getElementById("confirmPortfolio").onclick = submissionReceived;

            dowfirmPortfolio.addEventListener("click", addDowfolio);

        }
    });

    // Command and Flyout functions.
    function showDowfolioFlyout() {
        showFlyout(addDowPortfolioFlyout, dowButton, "top");
    }

    function showAddPortfolioFlyout() {
        showFlyout(addPortfolioFlyout, addButton, "top");
    }
    function showFlyout(flyout, anchor, placement) {
        flyout.winControl.show(anchor, placement);
    }

    function hideDowfolioFlyout() {
        hideFlyout(addDowPortfolioFlyout);
    }

    function hideAddPortfolioFlyout() {
        hideFlyout(addPortfolioFlyout);
    }
    function hideFlyout(flyout) {
        flyout.winControl.hide();
    }


    function doClickAdd() {
        showAddPortfolioFlyout();
    }

    function clickDowAdd() {
        showDowfolioFlyout();
    }

    function addDowfolio(event) {
        var name = dowfolioNameInput.value;

        var date = dowDatePicker.winControl.current;
        date = new FolioFixer.DataTypes.Date(date.getFullYear(), date.getMonth(), date.getDate() - 1);

        var numToSelect = new Number(numAssets.value);
        var selectorType = selection.value;

        var symbols;

        WinJS.xhr({
            url: "http://money.cnn.com/data/dow30/"
        }).then(function (html) {
            html = toStaticHTML(html.responseText);
            symbols = _.map($(html).find(".wsod_symbol"), function (element) {
                return element.text;
            });

            var assetQuery = symbols.join("+");

            return WinJS.xhr({
                url: "http://finance.yahoo.com/d/quotes.csv?s=" + assetQuery + "&f=" + selectorType
            });
        }).then(function (values) {
            values = values.responseText.split("\r\n");
            values = values.slice(0, values.length-1);
            var symbolValueMap = _.map(values, function (value, index) {
                return {symbol: symbols[index], value: value }
            });

            if (selectorType == "j1") {
                symbolValueMap.forEach(function (svm) {
                    var match = marketCapRegex.exec(svm.value);
                    var number = new Number(match[1]);
                    var scale = match[3];
                    var power;
                    switch (scale) {
                        case "M":   power = 6;  break;
                        case "B":   power = 9;  break;
                        case "T":   power = 12; break;
                        default:    power = 0;
                    }

                    number *= Math.pow(10, power);
                    svm.value = number;
                });
            } else if (selectorType == "m6" || selectorType == "m8") {
                symbolValueMap.forEach(function (svm) {
                    var match = percentRegex.exec(svm.value);
                    var i = 0;
                    var number = new Number(match[2]);
                    if (match[1] == "-") number = -number;
                    svm.value = number;
                });
            } else {
                symbolValueMap.forEach(function (svm) {
                    svm.value = new Number(svm.value);
                    if (isNaN(svm.value)) svm.value = 0;
                });
            }

            symbolValueMap = _.sortBy(symbolValueMap, function (svm) {
                return svm.value;
            });

            symbolValueMap = symbolValueMap.slice(symbolValueMap.length - numToSelect, symbolValueMap.length + 1);

            var useSymbols = _.map(symbolValueMap, function (svm) {
                return svm.symbol;
            });

            var portfolio = new FolioFixer.DataTypes.PortfolioInfo(name, date, useSymbols);

            return FolioFixer.Home.PortfolioSource.add(portfolio);
        }).done(
            function () {
                hideDowfolioFlyout();
            }
        );
    }

    function submissionReceived(event) {
        //var portfolioName = portfolioNameInput.value;
        var text = document.getElementById("portfolioNameInput").value;

        var datePicker = document.getElementById("startDatePicker").winControl;
        var date = datePicker.current;
        date = new FolioFixer.DataTypes.Date(date.getFullYear(), date.getMonth(), date.getDate()-1);

        var portfolio = new FolioFixer.DataTypes.PortfolioInfo(text, date, []);

        FolioFixer.Home.PortfolioSource.add(portfolio).done(function () {

            hideAddPortfolioFlyout();
        });

    }

    function navigateToPortfolio(portfolio) {
        WinJS.Navigation.navigate("/pages/portfoliospecs/portfoliospecs.html", { portfolio: portfolio });
    }

    //var publicMembers = { PortfolioSource: new FolioFixer.DataSources.IndexedDbDataSource(1, "portfolios") };
    var publicMembers = { PortfolioSource: new FolioFixer.DataSources.PortfolioDataSource() };
    WinJS.Namespace.define("FolioFixer.Home", publicMembers);

    function navFromList(eventInfo) {
        eventInfo.detail.itemPromise.done(function(item) {
            navigateToPortfolio(item.data);
        });
        
    }

    function manageSelected(eventInfo) {
        var detail = eventInfo.detail;

        var list = portfolioList.winControl;
        var i = 0;
    }

    
})();
